using System;
using System.IO;
using Cysharp.Threading.Tasks;
using Framework.StateMechine;
using Game.Hotfix;
using LitJson;
using UnityEngine;
using UnityEngine.Networking;

namespace Game.Hotfix
{
    public class HotfixPrepare : StateBase
    {
        private Game.Hotfix.Hotfix hotfix;
        
        public override async UniTask OnEnter(StateArgs _args)
        {
            Debug.Log("hotfix prepare.");
            EventsManager.Instance.Broadcast(new HotfixMsgEvent{ msg = "检测更新..."});
            
            hotfix = stateMachine.owner as Game.Hotfix.Hotfix;
            await base.OnEnter(_args);

            try
            {
                UnityWebRequest request = UnityWebRequest.Get(HotfixConst.hotfixCommand);
                request.timeout = 10;
                await request.SendWebRequest();
                
                Debug.Log($"get server dto message: {request.downloadHandler.text}");
                hotfix.hotfixServerDto = JsonMapper.ToObject<HotfixServerDto>(request.downloadHandler.text);
            }
            catch (Exception e)
            {
                Debug.Log($"get server dto error, error:  {e.Message}");
                return;
            }
            
            // 热更关闭，跳过
            if (!hotfix.hotfixServerDto.openHotfix || hotfix.hotfixServerDto.version == -1)
            {
                stateMachine.Change(HotfixState.End);
                return;
            }
            
            await LoadEngineVersion();
            await LoadHotfixVersion();
            
            stateMachine.Change(HotfixState.VerifyVersion);
        }
        
        // 原始版本号
        // 打包的时候把当时的资源版本号放入 ClientVersion.Version
        private async UniTask LoadEngineVersion()
        {
            await UniTask.CompletedTask;
            
            try
            {
                // int.TryParse(ClientVersion.Version, out hotfix.engineVersion);
                
                string version = File.ReadAllText(HotfixConst.engineVersionFile);
                hotfix.engineVersion = 0;
                int.TryParse(version, out hotfix.engineVersion);
            }
            catch (Exception e)
            {
                Debug.Log($"load engine version fail, reason: {e.Message}");
                hotfix.engineVersion = 0;
            }
        }
        
        // 当前热更过的资源版本号
        // 每次热更资源都会热更到
        private async UniTask LoadHotfixVersion()
        {
            await UniTask.CompletedTask;

            try
            {
                string version = File.ReadAllText(HotfixConst.hotfixVersionFile);
                hotfix.hotfixVersion = 0;
                int.TryParse(version, out hotfix.hotfixVersion);
            }
            catch (Exception e)
            {
                Debug.Log($"load hotfix version fail, reason: {e.Message}");
                hotfix.hotfixVersion = 0;
            }
        }
    }
}